//
//  LLTPhotoManager.swift
//  TakePhoto
//
//  Created by 李陆涛 on 2018/5/31.
//  Copyright © 2018年 llt. All rights reserved.
//

import Foundation
import Photos
import HXPhotoPicker

class LLTPhotoManager {
    
    //    MARK:请求权限
    
    /// 请求相册权限
    ///
    /// - Parameter handler: --
    class func requestPhotoLibraryAuthority(_ handler: @escaping (Bool) -> Swift.Void) {
        
        let status = PHPhotoLibrary.authorizationStatus()
        
        if status == .authorized {
            //            已经同意
            handler(true)
            
            return
        }
        
        if status == .denied {
            
            //            被显示拒绝，提示设置
            handler(false)
            
            return
        }
        
        PHPhotoLibrary.requestAuthorization { status in
            
            if (status == .authorized) {
                
                handler(true)
                
                return
            }
            
            handler(false)
            
        }
    }
    
    /// 请求相机权限
    ///
    /// - Parameter handler: --
    class func requestCameraAuthority(_ handler: @escaping (Bool) -> Swift.Void) {
        
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        
        if status == .authorized {
            //            已经同意
            handler(true)
            
            return
        }
        
        if status == .denied {
            
            //            被显示拒绝，提示设置
            handler(false)
            
            return
        }
        
        AVCaptureDevice.requestAccess(for: .video) { success in
            
            handler(success)
            
        }
    }
    
    
    /// 请求麦克风权限
    ///
    /// - Parameter handler: --
    class func requestMicrophoneAuthority(_ handler: @escaping (Bool) -> Swift.Void) {
        
        let status = AVCaptureDevice.authorizationStatus(for: .audio)
        
        if status == .authorized {
            //            已经同意
            handler(true)
            
            return
        }
        
        if status == .denied {
            
            //            被显示拒绝，提示设置
            handler(false)
            
            return
        }
        
        AVCaptureDevice.requestAccess(for: .audio) { success in
            
            handler(success)
            
        }
    }
    
    
    class func getVideocover(url:URL) -> UIImage? {
        
        let asset = AVURLAsset(url: url)
        let gen = AVAssetImageGenerator(asset: asset)
        gen.appliesPreferredTrackTransform = true
        
        let time = CMTime(seconds: 0.0, preferredTimescale: 600)
        
        guard let image = try? gen.copyCGImage(at: time, actualTime: nil) else {
            
            return nil
        }
        
        return UIImage(cgImage: image)

    }
    
    
    class func videoFolder() ->String {
        
        let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        
        var videoFolder = "\(docPath)/LLTVideo"
        
        let exist = FileManager.default.fileExists(atPath: videoFolder)
        if !exist {
            do {
                try FileManager.default.createDirectory(atPath: videoFolder, withIntermediateDirectories: true, attributes: nil)
            } catch {
                videoFolder = docPath
            }
        }
        
        return videoFolder
    }
    
    class func cropVideo(asset: AVAsset, cropRange:CMTimeRange, completion:((_ newUrl: URL, _ newDuration:CGFloat,_ result:Bool) -> ())?) {
        
//        let asset = AVURLAsset.init(url: url, options: nil)
        let duration = CGFloat(CMTimeGetSeconds(asset.duration))
        let newPath = "\(videoFolder())/\(UUID.init().uuidString).mp4"
        
        let outputUrl = URL.init(fileURLWithPath: newPath)
        let compatiblePresets = AVAssetExportSession.exportPresets(compatibleWith: asset)
        
        if !compatiblePresets.contains(AVAssetExportPresetMediumQuality) {
            
            completion?(outputUrl,duration,false)
           return
        }
        
        guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetMediumQuality) else {
            
            completion?(outputUrl,duration,false)
            return
        }
        exportSession.outputURL = outputUrl
        exportSession.outputFileType = AVFileType.mp4
        exportSession.shouldOptimizeForNetworkUse = true
        exportSession.timeRange = cropRange
//        exportSession.
        exportSession.exportAsynchronously {
            let status = exportSession.status
            switch status {
            case .failed:
                
                completion?(outputUrl,duration,false)
                break
            case .cancelled:
                
                completion?(outputUrl,duration,false)
                break
            case .completed:
                
                completion?(outputUrl,duration,true)
                break
            default:
                break
            }
        }
    }
    
    class func getVideoComposition(asset:AVAsset) {
        
        
    }
    
    
    class func getImage(with model:HXPhotoModel,completion:@escaping (UIImage?,HXPhotoModel?)-> Swift.Void) {

        if let asset = model.asset {
            
            HXPhotoTools.getHighQualityFormatPhoto(asset, size: model.requestSize, succeed: { image in
                
                completion(image, model)
            }) {
            
                completion(nil, model)
            }
            
            return;
            
        }
        completion(model.previewPhoto, model)
    }
}


